#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
下载引擎，负责处理视频下载逻辑
"""

import os
import time
import subprocess
import threading
import re

class DownloadEngine:
    """视频下载引擎"""
    
    def __init__(self):
        """初始化下载引擎"""
        self.is_cancelled = False
        self.process = None
    
    def download(self, url, save_path, progress_callback, logger):
        """
        下载视频
        
        Args:
            url: B站视频URL
            save_path: 保存路径
            progress_callback: 进度回调函数
            logger: 日志记录器
        """
        self.is_cancelled = False
        
        # 检查是否安装了you-get
        try:
            subprocess.run(["you-get", "--version"], 
                          stdout=subprocess.PIPE, 
                          stderr=subprocess.PIPE, 
                          check=True)
        except (subprocess.SubprocessError, FileNotFoundError):
            logger.error("未检测到you-get，正在尝试安装...")
            try:
                subprocess.run(["pip", "install", "you-get"], 
                              stdout=subprocess.PIPE, 
                              stderr=subprocess.PIPE, 
                              check=True)
                logger.info("you-get安装成功")
            except subprocess.SubprocessError:
                logger.error("安装you-get失败，请手动安装: pip install you-get")
                return
        
        # 开始下载
        logger.info(f"正在解析视频信息: {url}")
        
        try:
            # 获取视频信息
            info_process = subprocess.run(
                ["you-get", "-i", url],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
                encoding='utf-8'
            )
            
            if info_process.returncode != 0:
                logger.error(f"解析视频信息失败: {info_process.stderr}")
                return
            
            # 解析视频信息
            info_output = info_process.stdout
            logger.info("视频信息获取成功")
            
            # 提取视频标题
            title_match = re.search(r'Title:\s+(.+)', info_output)
            if title_match:
                title = title_match.group(1)
                logger.info(f"视频标题: {title}")
            
            # 提取视频大小
            size_match = re.search(r'Size:\s+(.+) \((.+)\)', info_output)
            if size_match:
                size = size_match.group(1)
                size_readable = size_match.group(2)
                logger.info(f"视频大小: {size_readable}")
            
            # 开始实际下载
            logger.info("开始下载视频...")
            
            # 创建下载命令
            download_cmd = ["you-get", "-o", save_path, url]
            
            # 启动下载进程
            self.process = subprocess.Popen(
                download_cmd,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                text=True,
                encoding='utf-8',
                bufsize=1,
                universal_newlines=True
            )
            
            # 模拟进度更新
            # 注意：you-get不提供实时进度信息，这里使用模拟进度
            progress = 0
            while self.process.poll() is None and not self.is_cancelled:
                line = self.process.stdout.readline()
                if line:
                    logger.info(line.strip())
                    
                    # 尝试从输出中解析进度
                    if "%" in line:
                        try:
                            percent_match = re.search(r'(\d+)%', line)
                            if percent_match:
                                progress = int(percent_match.group(1)) / 100
                                progress_callback(progress)
                        except:
                            # 如果解析失败，使用模拟进度
                            progress += 0.01
                            if progress > 0.95:
                                progress = 0.95
                            progress_callback(progress)
                    else:
                        # 如果没有进度信息，使用模拟进度
                        progress += 0.005
                        if progress > 0.95:
                            progress = 0.95
                        progress_callback(progress)
                else:
                    time.sleep(0.1)
            
            # 检查是否取消
            if self.is_cancelled:
                logger.info("下载已取消")
                return
            
            # 检查下载结果
            if self.process.returncode == 0:
                progress_callback(1.0)  # 设置进度为100%
                logger.success("视频下载完成")
            else:
                logger.error("下载失败")
        
        except Exception as e:
            logger.error(f"下载过程中发生错误: {str(e)}")
            if self.process:
                self.process.terminate()
    
    def cancel(self):
        """取消下载"""
        self.is_cancelled = True
        if self.process:
            self.process.terminate()